<?php


namespace app\helper;


use app\libs\Utils;
use app\model\AdminTenant;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use think\facade\Config;
use think\facade\Env;

class WxHelper
{
    public static function getWxUserInfo($appid,$appsecrt,$code)
    {
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid . "&secret=" . $appsecrt . "&code=" . $code . "&grant_type=authorization_code";
        $rjson = CommonHelper::http_curl($url);
        $access_token = $rjson['access_token'];//得到access_token ( 网页的)
        $openId = $rjson['openid'];//得到openid
        $userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openId&lang=zh_CN";//获取用户信息
        $result = CommonHelper::http_curl($userInfoUrl);
        return $result;
    }

    /**
     * @param $fid
     * @param \think\Request $request
     * @return array
     */
    public static function getWxPayConfig($fid,$request){
        $model = AdminTenant::get($fid);
        $data = $model->getData();
        if(Utils::isEmpty($data['wx_payment_key'])||Utils::isEmpty($data['wx_payment_merchant_id'])||Utils::isEmpty($data['wx_payment_cert_path'])||Utils::isEmpty($data['wx_payment_key_path'])){
            return ['done'=>false,'msg'=>'请先配置微信支付参数'];
        }
        $config = [
            // 必要配置
            'app_id'             => $data['gzh_appid'],
            'mch_id'             => $data['wx_payment_merchant_id'],
            'key'                => $data['wx_payment_key'],   // API 密钥
//            'sandbox' => true, // 设置为 false 或注释则关闭沙箱模式
            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            'cert_path'          => Env::get('root_path') . $data['wx_payment_cert_path'], // XXX: 绝对路径！！！！
            'key_path'           => Env::get('root_path') . $data['wx_payment_key_path'],      // XXX: 绝对路径！！！！

            'notify_url'         => $request->domain() . '/admin/Notify/wxPayNotify',     // 你也可以在下单时单独设置来想覆盖它
        ];
        return ['done'=>true,'config'=>$config];
    }

    private $config =null;
    private $wx =null;
    public  function getConfig($tid){
        if($this->config == null){
            $this->config = Config::get('wechat.officialAccount');
            $model = AdminTenant::get($tid);
            if($model){
                $data = $model->getData();
                $this->config['app_id'] = $data['gzh_appid'];
                $this->config['secret'] = $data['gzh_secret'];
                $this->config['token'] = $data['gzh_token'];
                $this->config['aes_key'] = $data['gzh_aes_key'];
            }
        }
        return $this->config;
    }
    /**
     * 懒加载获取easywechat操作的工厂类
     */
    public function getWx($tid){
        if($this->wx == null){
            $this->wx = Factory::OfficialAccount($this->getConfig($tid));;
        }
        return $this->wx;
    }

    /**
     * 发送模板消息
     * @param $tid
     * @param $openid
     * @param $tempate string 模板id
     * @param $data array
     */
    public function sendMsg($tid,$openid,$tempate,$data){
        try {
            $this->getWx($tid)->template_message->send([
                'touser' => $openid,
                'template_id' => $tempate,
                'data' => $data,
            ]);
        } catch (InvalidArgumentException $e) {
            //TODO 可以在这里做持久化或者重试
        }
    }
}